package com.cactus.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cactus.entity.User;
import com.cactus.mapper.UserMapper;
import com.cactus.service.AuthService;
import com.cactus.service.TUserService;
import com.cactus.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author: cactus
 * @CreateDate: 2023/9/14 11:52
 * @Description:
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TUserService tUserService;

    // 登录
    @Override
    public String login(String username) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, username);
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        final String token = jwtTokenUtil.generateToken(userDetails);
        return token;
    }

    // 注册
    @Override
    public void register(User userToAdd) {
        String username = userToAdd.getUsername();
        String userType = userToAdd.getUserType();
        if (userMapper.findByUsername(username, userType) != null) {
            throw new RuntimeException(username + " 账号已存在!");
        }
        userToAdd.setUid(IdWorker.getId() + "");
        userToAdd.setPassword(new BCryptPasswordEncoder().encode(username));
        userToAdd.setStatus(1);
        tUserService.save(userToAdd);

    }
}